
#import "APDiscoveryContetListLayout.h"
@interface APDiscoveryContetListLayout()
@property (nonatomic, strong) NSMutableArray *columnMaxYs;
@property (nonatomic, strong) NSMutableArray *itemAttributes;
@end

@implementation APDiscoveryContetListLayout
- (NSMutableArray *)columnMaxYs{
    if (!_columnMaxYs) {
        _columnMaxYs = [NSMutableArray arrayWithCapacity:_columns];
    }
    return _columnMaxYs;
}

- (NSMutableArray *)itemAttributes{
    if (!_itemAttributes) {
        _itemAttributes = [NSMutableArray array];
    }
    return _itemAttributes;
}
- (void)prepareLayout{
    [super prepareLayout];
    [self.columnMaxYs removeAllObjects];
    [self.itemAttributes removeAllObjects];
    for (NSInteger i = 0; i < _columns; i++) {
        CGFloat start = i == 1 ? 24:0;
        [self.columnMaxYs addObject:@(_sectionInsets.top + start)];
    }
    NSInteger num = [self.collectionView numberOfItemsInSection:0];
    for (NSInteger i = 0; i < num; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [self.itemAttributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }


}

- (CGSize)collectionViewContentSize{
    CGFloat maxY = 0;
    for (NSInteger i = 0; i < self.columnMaxYs.count; i++) {
        CGFloat temp = [[self.columnMaxYs objectAtIndex:i] floatValue];
        if (temp > maxY) {
            maxY = temp;
        }
    }
    return  CGSizeMake(self.collectionView.bounds.size.width, maxY + _sectionInsets.bottom);
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.itemAttributes;
}


- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    CGSize size = [self.delegate worksListView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
    CGRect frame;
    CGFloat x = 0;
    CGFloat y = 0;
    frame.size = size;
    NSInteger shortestColumnNumber = 0;//最短的列号
    CGFloat shortestColumnHeight = [[self.columnMaxYs objectAtIndex:shortestColumnNumber] floatValue];//最短的列高
    for (NSInteger i = 0; i < self.columnMaxYs.count; i++) {
        CGFloat temp = [[self.columnMaxYs objectAtIndex:i] floatValue];
        if (temp < shortestColumnHeight) {
            shortestColumnHeight = temp;
            shortestColumnNumber = i;
        }
    }
    x = _sectionInsets.left + shortestColumnNumber * size.width + shortestColumnNumber * _interitemSpace;
    if (indexPath.item >= 2) {
        y = shortestColumnHeight + _lineSpace;
    }else{
        y = shortestColumnHeight;
    }
    frame.origin = CGPointMake(x, y);
    attribute.frame = frame;
    self.columnMaxYs[shortestColumnNumber] = @(CGRectGetMaxY(attribute.frame));
    return attribute;
}

@end
